package com.fang.offer;

/**
 * <pre>
 * 题目描述
 * 给定一个double类型的浮点数base和int类型的整数exponent。求base的exponent次方。
 * </pre>
 *
 */
public class OfferPower {

	public static void main(String[] args) {
		System.out.println(OfferPower.Power(2, -1));
		System.out.println(OfferPower.Power(2, 0));
		System.out.println(OfferPower.Power(2, 1));
		System.out.println(OfferPower.Power(0, -1));

	}

	public static boolean g_invalidInput = false;

	public static double Power(double base, int exponent) {
		g_invalidInput = false;
		if (equal(base, 0.0)) {
			g_invalidInput = true;
			return 0;
		}
		int absExponent = Math.abs(exponent);
		double result = powerWithExponent2(base, absExponent);
		if (exponent < 0) {
			result = 1.0 / result;
		}
		return result;
	}

	private static double powerWithExponent(double base, int absExponent) {
		double result = 1.0;
		for (int i = 0; i < absExponent; i++) {
			result *= base;
		}
		return result;
	}

	private static double powerWithExponent2(double base, int absExponent) {
		if (absExponent == 0)
			return 1;
		if (absExponent == 1)
			return base;
		double result = powerWithExponent2(base, absExponent >> 1);
		result *= result;
		if ((absExponent & 0x1) == 1) {
			result *= base;
		}
		return result;
	}

	private static boolean equal(double num1, double num2) {
		if ((num1 - num2 > -0.000001) && (num1 - num2 < 0.000001)) {
			return true;
		} else {
			return false;
		}
	}
}
